#include "Log.hpp"
#include <string>
#include <sys/types.h>          
#include <sys/socket.h>
#include <cstring>
#include <netinet/in.h>
#include <strings.h>
#include <arpa/inet.h>
#include <functional>
#include <cstdio>


const int size = 1024;
std::string defaultip = "0.0.0.0";
uint16_t defaultport = 8080;

Log log;

enum
{
    SOCKET_ERR = 1,
    BIND_ERR
};

class UdpClient
{
public:
    UdpClient(const std::string& ip = defaultip, const uint16_t& port = defaultport)
        : _sockfd(0)
        , _ip(ip)
        , _port(port)
    {}

    void Init()
    {
        _sockfd = socket(AF_INET, SOCK_DGRAM, 0);
        if(_sockfd < 0)
        {
            log(Fatal, "socket create error, errno: %d, err string: %s", errno, strerror(errno));
            exit(SOCKET_ERR);
        }
    }

    void Run()
    {
        string message;
        char inbuffer[size];

        struct sockaddr_in server;
        bzero(&server, sizeof(server));
        server.sin_family = AF_INET;
        server.sin_port = htons(_port); //?
        server.sin_addr.s_addr = htonl(INADDR_ANY);
        socklen_t len = sizeof(server);

        while(true)
        {
            std::cout << "Please Enter@ " << std::endl;
            getline(cin, message);

            sendto(_sockfd, message.c_str(), message.size(), 0, (const sockaddr*)&server, len);

            struct sockaddr_in temp;
            socklen_t len = sizeof(temp);
            ssize_t n = recvfrom(_sockfd, inbuffer, sizeof(inbuffer), 0, (struct sockaddr*)&temp, &len);
            if(n > 0)
            {
                inbuffer[n] = 0;
                std::cout << inbuffer << std::endl;
            }
        }
    }

    ~UdpClient()
    {}

private:
    int _sockfd;            
    std::string _ip;        
    uint16_t _port;
};